import { RefObject, useEffect } from "react";

function useClickOutside(ref: RefObject<HTMLElement>, handler: Function) {
  useEffect(() => {
    const listener = (event: MouseEvent) => {
      event.stopPropagation();
      if (!ref.current || ref.current.contains((event.target) as HTMLElement ?? null)) {
        return;
      }
      handler(event);
    }
    document.addEventListener('click', listener);
    return () => {
      document.removeEventListener('click', listener);
    }
  }, [ref, handler]);
}

export default useClickOutside;